<template>
  <zm-view ref="view">
    <zm-navbar :border-bottom="false" back-icon-color="#ffffff" title-color="#ffffff" gradient gradient-heigt="50" :background="matchColor" :title="orderInfo.showStatusName">
      <template slot="right">
        <zm-icon v-if="isShowDelete" name="delete-o" color="#ffffff" size="36rpx" @click="handleDeleteOrder"></zm-icon>
      </template>
    </zm-navbar>
    <view class="head-bg" :style="[headBgStyle]"></view>
    <image class="head-image" :src="useImage('/zuimei-film-oss/1.0.0/images/film-order-top.png')"></image>
    <view class="content-wrap">
      <!-- 待支付 -->
      <view v-if="orderInfo.showStatus == 0" class="flex flex-col items-center">
        <view class="flex font-26 text-white">
          <text>请尽快完成付款，晚了就没座位了哦，还剩</text>
          <u-count-down :time="orderInfo.autoTime * 1000" auto-start format="mm分ss秒" @finish="handleGetInfo"></u-count-down>
        </view>
        <view class="flex mt-36 px-2">
          <zm-button
            type="default"
            round
            plain
            color="transparent"
            border-width="1rpx"
            text-color="#ffffff"
            border-color="#ffffff"
            width="252rpx"
            height="62rpx"
            font-size="26rpx"
            @click="cancelOrder"
            >取消订单</zm-button
          >
          <zm-button :disabled="payDisabled" type="default" round width="252rpx" height="62rpx" background="#ffffff" font-size="26rpx" custom-class="ml-36" @click="toPay">{{
            payText
          }}</zm-button>
        </view>
      </view>
      <!-- 待出票 -->
      <view v-if="orderInfo.showStatus == 1" class="font-26 text-center text-white"> 正在奋力出票中，预计需要1-3分钟... </view>
      <!-- 已出票 -->
      <view v-if="orderInfo.showStatus == 2" class="font-26 text-center text-white"> 订单出票成功，等待观影 </view>
      <!-- 已放映 -->
      <view v-if="orderInfo.showStatus == 3" class="font-26 text-center text-white"> 影片已放映，祝您观影愉快 </view>
      <!-- 购票失败 -->
      <view v-if="orderInfo.showStatus == 4" class="font-26 text-center text-white"> 系统正在为您自动退款，预计1-3个工作原路退回 </view>
      <!-- 已退款 -->
      <view v-if="orderInfo.showStatus == 5" class="font-26 text-center text-white"> 已完成退款，如有疑问请联系客服 </view>
      <!-- 电影信息 -->
      <view class="card-top">
        <view class="flex flex-1 items-center" @click="handleToCinema">
          <text class="text-white font-28 font-700 text-row-1 mr-10">{{ orderInfo.cinemaName }}</text>
          <zm-icon name="arrow" color="#ffffff" size="24rpx"></zm-icon>
        </view>
        <view class="line"></view>
        <view class="right shrink-0">
          <zm-icon :name="useImage('/zuimei-film-oss/1.0.0/icons/map-icon.png')" size="38rpx" @click="handleToCinemaMap"></zm-icon>
          <zm-icon :name="useImage('/zuimei-film-oss/1.0.0/icons/phone-icon.png')" color="#ffffff" size="38rpx" @click="handleCall"></zm-icon>
        </view>
      </view>
      <view class="card-bottom" :class="{ 'card-bottom--qrcode': showFilmQrCode }">
        <view class="flex flex-1 justify-between">
          <view class="flex flex-col flex-1">
            <text class="font-36 font-700">{{ orderInfo.filmName }}</text>
            <text class="mt-12 text-666">{{ orderInfo.copyLanguage }} {{ orderInfo.copyType }}</text>
            <view class="flex mt-20 text-666 mr-24">
              <text class="w-200 shrink-0">{{ orderInfo.sDate }}</text>
              <text class="hall-name">{{ orderInfo.hallName }}</text>
            </view>
          </view>
          <u-image :src="orderInfo.cover" width="106rpx" height="148rpx" radius="12rpx"></u-image>
        </view>
        <view class="flex mt-12">
          <text class="font-700 w-200 shrink-0">{{ orderInfo.sTime }}-{{ orderInfo.eTime }}</text>
          <text class="font-700">{{ orderInfo.seatDescribe }}</text>
        </view>
      </view>
      <!-- 取票二维码 ||  刷新出票状态-->
      <view v-show="showFilmQrCode || isWaitStatus" class="film-qrcode p-24 radius-12">
        <view class="line"></view>
        <view class="flex flex-1 justify-between">
          <text class="font-32 font-700">取电影票</text>
          <!-- #ifndef WEB -->
          <zm-icon v-if="showFilmShare" name="share-circle" size="40rpx" @click="handleShare"></zm-icon>
          <!-- #endif -->
        </view>
        <!-- 刷新出票状态 -->
        <view v-if="isWaitStatus" class="flex flex-col items-center">
          <image class="icon-paying mt-60" :src="useImage('/zuimei-film-oss/1.0.0/gif/paying.gif')" />
          <text class="text-666 font-26 pb-60 mt-20">出票中</text>
        </view>
        <!-- 取票二维码 -->
        <view v-show="showFilmQrCode" class="flex flex-col">
          <view class="flex flex-1 flex-col items-center">
            <view class="py-12 relative">
              <view class="flex" :class="{ 'opacity-4': isOpacity }">
                <zm-qrcode :value="orderInfo.qrCode" :size="244" @success="handleQrCodeResult" @error="handleQrCodeError"></zm-qrcode>
              </view>
              <!-- 已放映 -->
              <image v-if="orderInfo.showStatus == 3" class="tag-image" :src="useImage('/zuimei-film-oss/1.0.0/images/yfy-tag.png')" mode="scaleToFill" />
              <!-- 已退款 -->
              <image v-if="orderInfo.showStatus == 5" class="tag-image" :src="useImage('/zuimei-film-oss/1.0.0/images/ytk-tag.png')" mode="scaleToFill" />
            </view>
            <view class="flex flex-col items-center" :class="{ 'opacity-4': isOpacity }">
              <text v-if="orderInfo.ticketNum > 1" class="font-22 text-666">{{ orderInfo.ticketNum }}张电影票</text>
              <view class="code-btn">
                <view v-for="(item, index) in orderInfo.ticketInfo" :key="index" class="flex items-center">
                  <text> {{ item.name }} </text>
                  <text class="ml-10" :class="{ 'text-line-through': isCodeInvalid }"> {{ item.value }}</text>
                </view>
              </view>
              <text v-if="orderInfo.showStatus == 2" class="font-26 text-center px-60 mt-24 text-666">凭借该{{ ticketInfoText }}至影院自助机取票</text>
              <text v-if="orderInfo.showStatus == 4" class="font-26 text-center px-60 mt-24 text-666"> 很抱歉，影票出票失败正在为您自动退款，您可更换其他场次/影院重新选座购买 </text>
              <text v-if="orderInfo.showStatus == 5" class="font-26 text-center px-60 mt-24 text-666">已成功为您退款，如有疑问请联系客服</text>
              <text v-if="orderInfo.showStatus == 6" class="font-26 text-center px-60 mt-24 text-666">已成功取消订单，如有疑问请联系客服</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 订单信息 -->
      <view class="p-24 mt-20 bg-white radius-12">
        <view class="flex flex-1 justify-between">
          <text class="font-32 font-700">订单信息</text>
          <zm-icon-text name="arrow" text="金额明细" text-left text-size="26rpx" text-color="#666" size="26rpx" @click="showDetalPopup = true"></zm-icon-text>
        </view>
        <!--     <view class="flex font-26 mt-20 items-center">
          <text class="text-666">订单金额：</text>
          <text class="text-price-before ml-10 font-28">{{ orderInfo.asPrice | formatDigit }}</text>
        </view> -->
        <view class="flex font-26 mt-20 items-center">
          <text class="text-666">实付金额：</text>
          <text class="text-price-before ml-10 font-28">{{ orderInfo.tripartiteAmount | formatDigit }}</text>
        </view>
        <view class="flex font-26 mt-20 items-center">
          <text class="text-666">订单号码：</text>
          <text class="ml-10 font-28">{{ orderInfo.orderNo }}</text>
          <view class="copy-btn" @click="useCopy(orderInfo.orderNo)">复制</view>
        </view>
        <view class="flex font-26 mt-20 items-center">
          <text class="text-666">订单时间：</text>
          <text class="ml-10 font-28">{{ orderInfo.orderTime }}</text>
        </view>
        <view class="flex font-26 mt-20 items-center">
          <text class="text-666">手机号码：</text>
          <text class="ml-10 font-28">{{ orderInfo.lockMobile }}</text>
        </view>
      </view>

      <!-- 观影须知 -->
      <view class="p-24 mt-20 bg-white radius-12">
        <view class="flex flex-1 justify-between">
          <text class="font-32 font-700">观影须知</text>
        </view>
        <view class="mt-24">
          <zm-richtext :content="channelInfo.viewFilmExplain"></zm-richtext>
        </view>
      </view>

      <view class="kf-btn" @click="useServiceJump">
        <u-icon name="kefu-ermai" size="30rpx"></u-icon>
        <text class="ml-10">联系客服</text>
      </view>
    </view>
    <zm-popup :show.sync="showDetalPopup" mode="bottom" border-radius="16rpx" closeable safe-area-inset-bottom>
      <view slot="header" class="flex justify-center p-24 font-32">金额明细</view>
      <view class="p-24">
        <view class="flex justify-between font-26 mb-36">
          <text class="text-666">订单金额</text>
          <view class="flex">
            <text class="text-price-before">{{ orderInfo.asPrice }}</text>
            <text class="ml-8">({{ orderInfo.ticketNum }}张电影票)</text>
          </view>
        </view>
        <view v-for="(item, index) in orderInfo.otherPayInfo" :key="index" class="flex justify-between font-26 mb-36">
          <template v-if="item.k == 'openVipCard'">
            <text class="text-666 shrink-0">{{ item.name }}</text>
            <text>¥{{ Math.abs(item.v) }}</text>
          </template>
          <template v-else-if="item.k == 'couponPay'">
            <text class="text-666 shrink-0">{{ item.name }}</text>
            <view class="flex flex-col text-right flex-1 ml-24">
              <text class="text-theme">{{ item.value }}</text>
              <text class="ml-8">({{ item.no }})</text>
            </view>
          </template>

          <template v-else-if="item.k == 'cardPay'">
            <text class="text-666 shrink-0">{{ item.name }}</text>
            <view class="flex flex-col text-right flex-1 ml-24">
              <text class="text-theme">-￥{{ Math.abs(item.v) }}</text>
              <text class="ml-8">({{ item.no }})</text>
            </view>
          </template>
          <template v-else>
            <text class="text-666 shrink-0">{{ item.name }}</text>
            <text class="text-theme">-¥{{ Math.abs(item.v) }}</text>
          </template>
        </view>
        <view v-if="orderInfo.surplusPrice" class="flex justify-between font-26 mb-36">
          <text class="text-666">实际支付</text>
          <view class="flex">
            <text class="text-price-before">{{ orderInfo.surplusPrice }}</text>
          </view>
        </view>
      </view>
      <view slot="footer" class="p-24">
        <zm-button size="large" round @click="showDetalPopup = false">确定</zm-button>
      </view>
    </zm-popup>
    <!-- #ifndef WEB -->
    <!-- 颜色分析 -->
    <zm-color-analysis :url="orderInfo.cover" :max-colors="1" :match-colors="filmCoverColors" @finish="handleOnColorAnalysisFinish"></zm-color-analysis>
    <!-- 海报生成 -->
    <qrcode-poster ref="poster" :data="orderInfo"></qrcode-poster>
    <!-- #endif -->
    <!-- 支付组件 -->
    <pay-way-popup ref="pay" :has-balance-pay="false" :has-integral-pay="false"> </pay-way-popup>
  </zm-view>
</template>

<script>
import page from "@/mixins/page"
import hook from "@/mixins/hook"
import { mapGetters } from "vuex"
import { FILM_ORDER_STATUS } from "@/dict"
import QrcodePoster from "./components/qrcode-poster"
export default {
  components: { QrcodePoster },
  mixins: [page, hook],
  data() {
    return {
      FILM_ORDER_STATUS,
      matchColor: "#288E9B",
      orderId: "",
      orderInfo: { cover: "", cinemaName: "", qrCode: "" },
      qrcodeImagePath: "",
      showDetalPopup: false,
      timer: null
    }
  },
  computed: {
    ...mapGetters(["filmCoverColors", "userInfo", "channelInfo", "webEvn"]),
    payText() {
      return this.webEvn == "ibl" ? "无法兑换" : "立即付款"
    },
    payDisabled() {
      return this.webEvn == "ibl"
    },
    headBgStyle() {
      const style = {}
      style.background = `linear-gradient(180deg, ${this.matchColor} 0%, ${this.matchColor} 50%, ${this.matchColor} 75%, ${this.useColor("page")} 100%)`
      return style
    },
    showFilmQrCode() {
      const status = ["2", "3", "5"]
      return status.includes(this.orderInfo.showStatus) && this.orderInfo.qrCode
    },
    showFilmShare() {
      const status = ["3", "5"]
      return !status.includes(this.orderInfo.showStatus) && this.orderInfo.qrCode
    },
    isCodeInvalid() {
      const status = ["3", "4", "5"]
      return status.includes(this.orderInfo.showStatus)
    },
    isOpacity() {
      const status = ["3", "4", "5"]
      return status.includes(this.orderInfo.showStatus)
    },
    ticketInfoText() {
      return this.orderInfo.ticketInfo?.map((item) => item.name).join("、")
    },
    isShowDelete() {
      const status = ["1", "2"]
      return !status.includes(this.orderInfo.showStatus)
    },
    isWaitStatus() {
      return this.orderInfo.showStatus == "1"
    }
  },
  onLoad(options) {
    this.orderId = options.orderId
  },
  onShow() {
    this.handleGetInfo()
  },
  onPullDownRefresh() {
    this.handleGetInfo()
  },
  methods: {
    async handleGetInfo() {
      await this.$nextTick()
      uni.$api.orderFilm
        .getOrderFilmInfo({ orderId: this.orderId })
        .then((res) => {
          this.orderInfo = res
          // 支付状态刷新
          if (this.orderInfo.showStatus == 1) {
            this.getFilmOrderStatus()
          }
          // 实际支付金额
          const surplusPrice = res.otherPayInfo?.find((item) => item.k == "surplusPrice")
          if (surplusPrice) this.orderInfo.surplusPrice = surplusPrice.v
          // 去除不显示支付项
          const keys = ["surplusPrice", "businessServicePrice"]
          this.orderInfo.otherPayInfo = res.otherPayInfo?.filter((item) => !keys.includes(item.k))
          setTimeout(() => {
            this.$forceUpdate()
          }, 300)
          uni.stopPullDownRefresh()
        })
        .catch(() => {
          uni.stopPullDownRefresh()
        })
    },
    // 颜色分析结果
    handleOnColorAnalysisFinish(colors) {
      if (colors?.length) {
        this.matchColor = colors[0]
      }
    },
    // 二维码生成结果
    handleQrCodeResult(path) {
      this.qrcodeImagePath = path
    },
    handleQrCodeError(error) {
      console.error(error)
    },
    // 处理分享
    handleShare() {
      this.$refs.poster.draw()
    },
    // 取消订单
    cancelOrder() {
      uni
        .$confirm({
          content: "是否取消订单"
        })
        .then(() => {
          uni.$api.orderFilm.unLockSeat({ orderId: this.orderId }).then(() => {
            uni.$toast({ type: "success", content: "操作成功" })
            this.handleGetInfo()
          })
        })
    },
    // 继续支付
    toPay() {
      if (this.orderInfo.lockJumpPay) {
        this.useAskToOSSJump(this.data.lockJumpPay)
      } else {
        this.$refs.pay.open({
          jumpType: "reLaunch",
          orderType: "film",
          filmOrderId: this.orderId,
          isContinuePay: true,
          orderId: this.orderId,
          preInfo: {
            needPay: this.orderInfo?.surplusPrice || this.orderInfo.salePrice
          }
        })
      }
    },
    // 删除订单
    async handleDeleteOrder() {
      uni.$dialog({
        title: "提示",
        content: "确定删除该订单吗?",
        asyncClose: true,
        showConfirmButton: true,
        showCancelButton: true,
        confirmButtonText: "确定删除",
        onConfirm: ({ close, done }) => {
          uni.$api.orderFilm
            .delOrder({ orderId: this.orderId })
            .then(() => {
              close()
              uni.navigateBack()
            })
            .catch(() => {
              done()
            })
        },
        onCancel: ({ close }) => {
          close()
        }
      })
    },
    handleToCinema() {
      this.toView({
        url: `pages/cinema/cinema-schedule/cinema-schedule`,
        params: { cinemaId: this.orderInfo.cinemaId }
      })
    },
    handleCall() {
      if (this.orderInfo.cinemaInfo?.serviceTel) {
        uni.makePhoneCall({
          phoneNumber: this.orderInfo.cinemaInfo.serviceTel
        })
      } else {
        uni.$toast("暂无联系电话")
      }
    },
    handleToCinemaMap() {
      this.toView({
        url: "pages/utils/map/map",
        params: {
          title: "影院位置",
          latitude: this.orderInfo.cinemaInfo.latitude,
          longitude: this.orderInfo.cinemaInfo.longitude,
          markerTitle: this.orderInfo.cinemaInfo.cinemaName
        }
      })
    },

    getFilmOrderStatus() {
      this.timer = setTimeout(() => {
        this.timer && clearTimeout(this.timer)
        uni.$api.orderFilm
          .getOrderStatus({ orderId: this.orderId })
          .then((res) => {
            const orderStatus = res.orderStatus
            if (["4", "5", "3"].includes(orderStatus)) {
              this.timer && clearTimeout(this.timer)
              this.handleGetInfo()
              this.$store.dispatch("getUserInfo")
            } else {
              this.getFilmOrderStatus()
            }
          })
          .catch(() => {
            this.getFilmOrderStatus()
          })
      }, 2000)
    }
  }
}
</script>

<style lang="scss" scoped>
.head-bg {
  top: 0;
  left: 0;
  width: 100%;
  height: 550rpx;
  position: absolute;
}
.head-image {
  top: 0;
  right: 0;
  width: 390rpx;
  height: 260rpx;
  position: fixed;
}
.content-wrap {
  padding: 24rpx;
  position: relative;

  .card-top {
    opacity: 0.4;
    display: flex;
    padding: 24rpx;
    margin-top: 38rpx;
    align-items: center;
    padding-bottom: 40rpx;
    background-color: #000000;
    justify-content: space-between;
    border-top-left-radius: 16rpx;
    border-top-right-radius: 16rpx;
    .line {
      width: 2rpx;
      height: 36rpx;
      opacity: 0.2;
      background-color: #fff;
    }
    .right {
      gap: 40rpx;
      height: 100%;
      display: grid;
      padding-left: 45rpx;
      align-items: center;
      grid-template-columns: repeat(2, 38rpx);
    }
  }
  .icon-paying {
    width: 484rpx;
    height: 289rpx;
  }
  .card-bottom {
    z-index: 1;
    overflow: hidden;
    margin-top: -16rpx;
    position: relative;
    padding: 40rpx 24rpx;
    border-radius: 16rpx;
    .hall-name {
      line-break: auto;
    }

    &:not(.card-bottom--qrcode) {
      background-color: #fff;
    }

    &--qrcode {
      &::before,
      &::after {
        top: 0;
        width: 50%;
        bottom: 0;
        content: "";
        z-index: -1;
        position: absolute;
      }

      &::before {
        left: 0;
        background-image: radial-gradient(circle at left bottom, transparent 14rpx, #fff 14rpx);
      }

      &::after {
        right: 0;
        background-image: radial-gradient(circle at right bottom, transparent 14rpx, #fff 14rpx);
      }
    }

    .w-200 {
      width: 200rpx;
    }
  }

  .film-qrcode {
    z-index: 1;
    overflow: hidden;
    position: relative;
    padding-bottom: 60rpx;
    border-bottom-left-radius: 16rpx;
    border-bottom-right-radius: 16rpx;

    &::before,
    &::after {
      top: 0;
      width: 50%;
      bottom: 0;
      content: "";
      z-index: -1;
      position: absolute;
    }

    &::before {
      left: 0;
      background-image: radial-gradient(circle at left top, transparent 14rpx, #fff 14rpx);
    }

    &::after {
      right: 0;
      background-image: radial-gradient(circle at right top, transparent 14rpx, #fff 14rpx);
    }

    .line {
      top: 0;
      left: 14rpx;
      right: 14rpx;
      position: absolute;
      border-top: 5rpx dashed #eeeeee;
    }

    .code-btn {
      gap: 12rpx;
      display: grid;
      font-size: 30rpx;
      font-weight: bold;
      margin-top: 25rpx;
      text-align: center;
      padding: 24rpx 46rpx;
      border-radius: 16rpx;
      background-color: #f4f6f7;
    }

    .tag-image {
      width: 180rpx;
      height: 180rpx;
      right: -50%;
      bottom: -15%;
      opacity: 1;
      position: absolute;
    }
  }

  .copy-btn {
    width: 56rpx;
    height: 30rpx;
    display: flex;
    align-items: center;
    border-radius: 4rpx;
    justify-content: center;
    border: 2rpx solid #cccccc;
    font-size: 22rpx;
    color: #999999;
    margin-left: 14rpx;
  }

  .kf-btn {
    width: 230rpx;
    font-size: 26rpx;
    height: 62rpx;
    display: flex;
    margin: auto;
    margin-top: 40rpx;
    margin-bottom: 30rpx;
    align-items: center;
    padding: 0 42rpx;
    background: #ffffff;
    border-radius: 36rpx;
  }
}
</style>
